#include "window.h"
#include <iostream>
#include "IslandApp.h"

Window* Window::pWnd = 0;


void Window::setInputReady(bool val) 
{ 
	input_ready = val; 
}



void Window::initialise(HINSTANCE hIstance, HWND& mWnd, int nCmdShow, int x, int y, int width, int height, IslandApp* app_ref)
{
	
	app = app_ref;
	Window::pWnd = this;
	this->x = x;
	this->y = y;

	bool res = InitWindow( hIstance, mWnd, nCmdShow, x, y, width, height);
}


Window::Window() : input_ready(0), app(0), x(0), y(0)
{

}

bool Window::InitWindow(HINSTANCE hInstance,HWND& mWnd, int nCmdShow, int x, int y, int width, int height) const
{
	WNDCLASSEX wc;
	
	wc.cbSize = sizeof(WNDCLASSEX);
	wc.style = CS_HREDRAW | CS_VREDRAW;;
	wc.lpfnWndProc = WindowProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon(0, IDI_APPLICATION);
	wc.hCursor = LoadCursor(0, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
	wc.lpszClassName = L"ClassName";
	wc.lpszMenuName = 0;
	wc.hIconSm = 0;
	
	RECT R = { 0, 0, width, height };
    AdjustWindowRect(&R, WS_OVERLAPPEDWINDOW, false);
	int w_width  = R.right - R.left;
	int w_height = R.bottom - R.top;

	if (!RegisterClassEx(&wc))
	{
		MessageBox(0, L"Error @ RegisterClassEx", L"Error", 1);
		return false;
	}
	
	if ((mWnd = CreateWindow(L"ClassName", L"App", WS_VISIBLE | WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, //WS_OVERLAPPEDWINDOW,
						x, y, w_width, w_height,
						0, 0, hInstance, 0)) == 0)
	{
		MessageBox(0, L"Error @ CreateWindow", L"Error", 1);
		return false;
	}

	ShowWindow(mWnd, nCmdShow);
	UpdateWindow(mWnd);

	return true;
}





LRESULT CALLBACK Window::WindowProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{		
	return Window::pWnd->wndWindowProc(hWnd, message, wParam, lParam);
}

LRESULT CALLBACK Window::wndWindowProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
	PAINTSTRUCT ps;
	HDC hdc;

	switch( message )
	{
		case WM_PAINT:
			hdc = BeginPaint( hWnd, &ps );
			EndPaint( hWnd, &ps );
			break;
		
		case WM_DESTROY:
			PostQuitMessage( 0 );
			break;
		
		case WM_CHAR:
			app->onKey(wParam);
			break;

		case WM_KEYDOWN:
			app->onKey(wParam);
			break;
		
		default:
			return DefWindowProc( hWnd, message, wParam, lParam );
	}
	return 0;
}